dojo.require("dojo.io.script");
dojo.addOnLoad(function () {
    dojo.io.script.get({url:"js/chat.js"});
});

cr = dojo.create;
$ = dojo.byId;

function call(method, params, callback) {
    require(["dojo/_base/lang", "dojo/_base/xhr"], function (lang, xhr) {
        xhr.post({
            url:"/" + method,
            handleAs:"json",
            content:params,
            load:function (data, ioArgs) {
                if (callback) {
                    callback(data ? data : {});
                }
                console.log(data);
            },
            error:function (err, ioArgs) {
                console.error(err);
            }
        });
    });
}

function callgo(method, params) {
    call(method, params ? params : {}, function (game) {
        refresh();
    });
}

function start() {
    initInterface();
    refresh();
}


function initInterface() {
    var div = cr("div", {style:"width:100%", align:"center"}, document.body);
    var table = cr("table", {width:"80%", border:"1"}, div);
    var tr = cr("tr", {}, table);
    cr("td", {id:"leftMain", style:"width:300px;"}, tr);
    cr("td", {id:"rightMain"}, tr);
}

function refresh() {
    call("get-user-game", {}, function (game) {
        switch (game.state.name) {
            case "no game" :
                buildPreRegistrationInGame();
                chat.on();
                break;
            case "queue" :
                buildQueue(game);
                chat.on();
                break;
            case "sharing" :
                buildSharing(game);
                chat.off();
                break;
            default :
                console.log("undefined game state:" + game.state);
        }

        setTimeout(refresh, 3000);
    });
}

function registerInGame() {
    callgo("register-in-game");
}

function unregisteredFromGame() {
    callgo("unregistered-from-game");
}


function buildQueue(game) {
    var parent = $("leftMain");
    parent.innerHTML = "";
    cr("div", {innerHTML:"You are registered in game: " + game.name + " waiting for all users"}, parent);

    cr("div", {innerHTML:"Users: " + _.map(game.users, function (n) {
        return n.username;
    })}, parent);
    cr("input", {type:"button", value:"Unregistered", onclick:unregisteredFromGame}, parent);
}

function buildSharing(game) {
    var parent = $("leftMain");
    parent.innerHTML = "";
    cr("div", {innerHTML:"Sharing"}, parent);

    ///cr("div", {innerHTML:"Users: " + _.pluck(game.users, "username")}, parent);
    //cr("input", {type:"button", value:"Unregistered", onclick:unregisteredFromGame}, parent);
}

function buildPreRegistrationInGame() {
    var parent = $("leftMain");
    parent.innerHTML = "";
    cr("input", {type:"button", value:"Register in game", onclick:registerInGame}, parent);
}


dojo.ready(start);
